<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/28
 * Time: 15:03
 */

namespace app\index\model;
use think\Model;
use think\Db;
class UsersModel extends Model
{
    // 确定链接表名
    protected $table = 'snake_users';
    public function recode($uid){
        $recode=$this->where(array('user_id'=>$uid))->value('recode');

        if(!is_null($recode) && $recode==''){
            $this->updateUser(array('recode'=>base64_encode($uid)),$uid);
        }
    }
    public function statistics(){
        $user_id=session('user_id');
        $ret=array(
            'newLoan'=>0,
            'newCard'=>0,
            'newVip'=>0
        );
        $curday=date('Y-m-d');
        $ret['newLoan']=Db::name('apply')->where(array('first_leader'=>$user_id,'type'=>1,"FROM_UNIXTIME(addtime,'%Y-%m-%d')"=>$curday))->count();
        $ret['newCard']=Db::name('apply')->where(array('first_leader'=>$user_id,'type'=>0,"FROM_UNIXTIME(addtime,'%Y-%m-%d')"=>$curday))->count();
        $ret['newVip']=Db::name('order')->where(array('first_leader'=>$user_id,'type'=>0,'status'=>1,"FROM_UNIXTIME(addtime,'%Y-%m-%d')"=>$curday))->count();
        return $ret;
    }
    public function myMsg($param){
        $user_id=session('user_id');
        $ret= Db::name('push')->where(array('to_user'=>$user_id))->order('addtime DESC,id DESC')->select();
        foreach ($ret as $k=>$vo){
            if($vo['title']=='') $ret[$k]['tilte']='系统消息';
            $ret[$k]['addtime']=format_date($vo['addtime']);
        }
        return $ret;
    }

    //注册
    public function register($param){
        //验证是否存在用户名

        $smsLogModel=new SmsLogModel();
        $smsLog=$smsLogModel->findSmsLog($param);
        if($param['code'] != $smsLog['code']){
            return msg(-5, '', '验证码错误');
        }

        $map=array(
            'password'=>md5($param['password']),
            'last_login'=>time(),
            'last_ip'=>request()->ip()
        );
        $hasUser = $this->findUserByMobile($param['mobile']);
        if(!empty($hasUser)){
            $ret=$this->updateUser($map,$hasUser['user_id']);
            if($ret['code']==1){
                $user_id=$hasUser['user_id'];
            }else{
                return msg(-4, '', '注册失败');
            }
        }else{
            $map['mobile']=$param['mobile'];
            $map['nickname']=substr_replace($param['mobile'],'****',3,4);
            $map['reg_time']=time();
            $user_id = $this->insertGetId($map);
            if($user_id === false)
                return msg(-4, '', '注册失败');
            $this->updateUser(array('recode'=>base64_encode($user_id)),$user_id);
        }
        session('user_id', $user_id);
        return msg(1, array('user_id'=>$user_id), '注册成功');
    }
    //登录
    public function login($param){
        $hasUser = $this->findUserByMobile($param['mobile']);
        if(empty($hasUser)){
            return msg(-3, '', '用户不存在');
        }
        if(md5($param['password']) != $hasUser['password']){
            return msg(-4, '', '密码错误');
        }
        // 更新用户数据
        $param = [
            'last_ip' => request()->ip(),
            'last_login' => time()
        ];
        $res = $this->updateUser($param, $hasUser['user_id']);
        if(1 != $res['code']){
            return msg(-6, '', $res['msg']);
        }
        $data['user_id']=$hasUser['user_id'];
        session('user_id', $hasUser['user_id']);
        return msg(1,$data , '登录成功');
    }
    public function bindMobile($param){

    }
    public function profile($param){
        $user_id=session('user_id');
        $this->updateUser($param,$user_id);
    }
    public function getMyVip($user_id){
        $level=$this->where(array('user_id'=>$user_id))->value('level');
        $ret=Db::name('user_level')->where(array('level'=>$level))->find();
        if(empty($ret)){
            $ret=array('level'=>0,'name'=>'普通会员','desc'=>'');
        }
        return $ret;
    }
    public function modifyPassword($param){
        //验证两次密码是否匹配
        if($param['password2'] != $param['password'])
            return msg(-2, '', '两次输入密码不一致');
        if(!checkMobileVerifyCode(array('session_id'=>$param['session_id'],'mobile'=>$param['mobile'],'code'=>$param['code']))){
            return msg(-5, '', '验证码错误');
        }
        $map=array(
            'mobile'=>$param['mobile'],
            'password'=>md5($param['password']),
            'last_login'=>time(),
            'last_ip'=>request()->ip()
        );
        //验证是否存在用户名
        $hasUser = $this->findUserByMobile($param['mobile']);
        if(!empty($hasUser)){
            $this->updateUser($map,$hasUser['user_id']);
            return msg(1, array('user_id'=>$hasUser['user_id']), '修改成功');
        }else{
            return msg(-3, '', '账号信息错误');
        }
    }

    public function changeMobile($param){
        $user = $this->findUserById($param['user_id']);
        if($user['mobile']!=$param['mobile']) return msg(-1, '', '原始手机号错误');
        //验证是否存在用户名
        $smsLogModel=new SmsLogModel();
        $smsLog=$smsLogModel->findSmsLog($param);
        if($param['code'] != $smsLog['code']){
            return msg(-5, '', '验证码错误');
        }
        return $this->updateUser(array('mobile'=>$param['new_mobile']),$param['user_id']);
    }

    public function hasExistedUserid($user_id){
        $tag=false;
        if($this->where(array('user_id'=>$user_id))->count()>0) $tag=true;
        return $tag;
    }
    /*
    public function insertGetId($param=[]){
        $this->save($param);
        $user_id=$this->user_id;
        return $user_id;
    }
    */
    public function getOne($id){
        return $this->where('user_id', $id)->find();
    }
    public function findUserById($user_id){
        $result= $this->where('user_id', $user_id)->find();
        if(!empty($result)){
            $result['head_pic']=head_pic($result['head_pic']);
            $result['level_tag']=level_tag($result['level']);
        }
        return $result;
    }
    public function findUpuserById($user_id){
        $first_leader=$this->where(array('user_id'=>$user_id))->value('first_leader');
        if(is_null($first_leader)) return array();
        $result= $this->where('user_id', $first_leader)->find();
        if(!empty($result)){
            $result['head_pic']=head_pic($result['head_pic']);
            $result['wxqr']=head_pic($result['wxqr']);
            $result['team_count']=$this->where("first_leader=$user_id OR second_leader=$user_id")->count()+1;
            $result['level_tag']=level_tag($result['level']);
        }
        return $result;
    }

    /**
     * 根据手机号获取用户信息
     * @param $name
     */
    public function findUserByMobile($mobile){
        return $this->where('mobile', $mobile)->find();
    }
    public function findUserByWhere($map){
        return $this->where($map)->find();
    }

    public function getUsers($param){
        $pageNo=1;$pageSize=10;
        if(isset($param['pageNo']) && $param['pageNo']!='' && $param['pageNo']>1) $pageNo=intval($param['pageNo']);
        if(isset($param['pageSize']) && $param['pageSize']!='' && $param['pageSize']>0) $pageSize=intval($param['pageSize']);
        $where='status=1';
        $list=$this->field('user_id,nickname,head_pic,sex,mobile,region,is_cert')
            ->where($where)
            ->order('reg_time DESC,user_id DESC')
            ->limit(($pageNo-1)*$pageSize,$pageSize)
            ->select();
        if(empty($list)) return array();
        foreach($list as $k=>$vo){
            $list[$k]['head_pic']=imageUrl($vo['head_pic']);
            if($vo['sex']==0) $list[$k]['sex']=1;
        }
        return $list;
    }

    /*
     * 更新用户状态状态
     * @param array $param
     */
    public function updateUser($param = [], $uid)
    {
        try{
            $this->where('user_id', $uid)->update($param);
            return msg(1, array('user_id'=>$uid), '更新成功');
        }catch (\Exception $e){

            return msg(-1, '', $e->getMessage());
        }
    }

    //实名认证
    public function idCert($param){
        $files=input('file.');
        $filter=array('card_face','card_back');
        if(!isset($files['card_face']) || !isset($files['card_back'])) return msg(-1,'','提交的身份认证信息不全');
        foreach($files as $k=>$v){
            if(in_array($k,$filter)){
                $file = request()->file($k);
                if($file !=false){
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $file->move(ROOT_PATH. 'upload'.DS . 'cert');
                    if($info){
                        $param[$k] =  '/upload' . '/cert/' . date('Ymd') . '/' . $info->getFilename();
                    }
                }
            }
        }
        if(!isset($param['card_face']) ||  !isset($param['card_back'])) return msg(-1,'','提交的身份认证信息不全');
        $param['status']=$param['is_cert'];
        $param['addtime']=time();
        try{
            $this->updateUser(array('age'=>$param['age'],'region'=>$param['region'],'sex'=>$param['sex'],'is_cert'=>$param['is_cert']),$param['user_id']);
            $result = Db::name('user_idcert')->insert($param);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', '未知错误');
            }
            $this->updateUser(array('is_cert'=>$param['is_cert']),['user_id'=>$param['user_id']]);
            return msg(1, $result, '提交成功');
        }catch(\Exception $e){
            return msg(-2, '', $e->getMessage());
        }
    }

    //是否有发布权限
    function isCert($user_id){
        $return=$this->field('is_cert')->where(array('user_id'=>$user_id))->find();
        if(!empty($return)){
            if($return['is_cert']==1){
                return true;
            }
        }
        return false;
    }

    //余额明细
    public function getMyMoneyRecord($param){
        $pageNo=1;$pageSize=10;
        if(isset($param['pageNo']) && $param['pageNo']!='' && $param['pageNo']>1) $pageNo=intval($param['pageNo']);
        if(isset($param['pageSize']) && $param['pageSize']!='' && $param['pageSize']>0) $pageSize=intval($param['pageSize']);
        $result=Db::name('user_money')->field('id,name,money,addtime,type')->where(array('user_id'=>$param['user_id']))
            ->order('addtime DESC,id DESC')
            ->limit(($pageNo-1)*$pageSize,$pageSize)
            ->select();
        return $result;
    }

    //公告
    public function getMyNotice($param){
        $pageNo=1;$pageSize=10;
        if(isset($param['pageNo']) && $param['pageNo']!='' && $param['pageNo']>1) $pageNo=intval($param['pageNo']);
        if(isset($param['pageSize']) && $param['pageSize']!='' && $param['pageSize']>0) $pageSize=intval($param['pageSize']);
        $result=Db::name('push')->field('id,title,message,addtime')->where("to_user=0 OR to_user=".$param['user_id'])
            ->order('addtime DESC,id DESC')
            ->limit(($pageNo-1)*$pageSize,$pageSize)
            ->select();
        return $result;
    }

    //投诉用户
    public function complainUser($param){
        if(!isset($param['complain_user_id']) || $param['complain_user_id']=='' || $param['complain_user_id']<=0 || !isset($param['complain_type']) || $param['complain_type']=='' || !isset($param['content']) || $param['content']==''){
            return msg(-1, '', '参数错误');
        }
        $hasComplainUser=$this->hasUserByUserid($param['complain_user_id']);
        if(empty($hasComplainUser)){
            return msg(-1, '', '您投诉的用户不存在');
        }
        try{
            $param['type']=2;
            $param['addtime']=time();
            $result = Db::name('feedback')->insert($param);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', '未知错误');
            }
            return msg(1, $result, '投诉成功');
        }catch(\Exception $e){
            return msg(-2, '', $e->getMessage());
        }
    }
    //投诉中心
    public function getMyLastComplain($param){
        $return= Db::name('feedback')->where(array('user_id'=>$param['user_id'],'type'=>2))->order('addtime DESC')->find();
        if(!empty($return)){
            //处理状态,0-待处理,1-正在处理,2-已处理
            if($return['status']==0 && $return['addtime']>=time()+2*60*60) $return['status']=1;
            $return=array('content'=>$return['content'],'complain_type'=>$return['complain_type'],'status'=>$return['status'],'reply'=>$return['reply']);
        }
        return $return;
    }
    //投诉历史记录
    public function getMyComplainHistory($param){
        $pageNo=1;$pageSize=10;
        if(isset($param['pageNo']) && $param['pageNo']!='' && $param['pageNo']>1){
            $pageNo=intval($param['pageNo']);
        }
        if(isset($param['pageSize']) && $param['pageSize']!='' && $param['pageSize']>0){
            $pageSize=intval($param['pageSize']);
            if($pageSize>100){
                $pageSize=100;
            }
        }
        $startRow=($pageNo-1)*$pageSize;
        $return= Db::name('feedback')->where(array('user_id'=>$param['user_id'],'type'=>2))->order('addtime DESC')->limit("$startRow,$pageSize")->select();
        if(!empty($return)){
            foreach($return as $k=>$v){
                //处理状态,0-待处理,1-正在处理,2-已处理
                if($v['status']==0 && $v['addtime']>=time()+2*60*60) $v['status']=1;
                $return[$k]=array('content'=>$v['content'],'complain_type'=>$v['complain_type'],'status'=>$v['status'],'addtime'=>$v['addtime'],'reply'=>$v['reply'],'replytime'=>$v['replytime']);
            }
        }
        return $return;
    }

    //反馈
    public function feedback($param){
        if(!isset($param['content']) || trim($param['content'])==''){
            return msg(-1, '', '请填写反馈信息');
        }
        try{
            $param['type']=1;
            $param['addtime']=time();
            $result = Db::name('feedback')->insert($param);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', '未知错误');
            }
            return msg(1, $result, '反馈成功');
        }catch(\Exception $e){
            return msg(-2, '', $e->getMessage());
        }
    }

    //获取提现信息
    public function getCashInfo($user_id){
        $conf=json_decode(Db::name('config')->where(array('inc_type'=>'cashInfo'))->value('value'),true);
        $result=array(
            'user_money'=>0,
            'bank_name'=>'支付宝',
            'bank_card'=>'',
            'realname'=>'',
            //'remark'=>'',
            'taxfee'=>$conf['taxfee'],
            'limitation'=>$conf['minimum'],
            'minimum'=>$conf['minimum'],
            'maximum'=>$conf['maximum'],
        );
        $result['user_money']=$this->where(array('user_id'=>$user_id))->value('user_money');
        $record=Db::name('user_cash')->where(array('user_id'=>$user_id))->order('id DESC')->find();
        if(!empty($record)){
            $result['bank_name']=$record['bank_name'];
            $result['bank_card']=$record['bank_card'];
            $result['realname']=$record['realname'];
        }
        return $result;
    }

    //提现记录
    public function getMyCashOrder($param){
        $pageNo=1;$pageSize=10;$param['type']=2;//提现成功
        if(isset($param['pageNo']) && $param['pageNo']!='' && $param['pageNo']>1){
            $pageNo=intval($param['pageNo']);
        }
        if(isset($param['pageSize']) && $param['pageSize']!='' && $param['pageSize']>0){
            $pageSize=intval($param['pageSize']);
        }
        $where=array('user_id'=>$param['user_id']);
        if(isset($param['type']) && $param['type']!=0 && $param['type']!=''){
            $where['status']=$param['type'];
        }
        $result=Db::name('user_cash')->where($where)->order('id DESC')->limit(($pageNo-1)*$pageSize,$pageSize)->select();
        foreach($result as $key=>$vo){
            //$result[$key]['type']=cashType($vo['status']);
        }
        return $result;
    }

    //生成提现订单
    public function addCashOrder($param){
        $user=$this->field('pay_deposit,deposit')->where(array('user_id'=>$param['user_id']))->find();
        if($user['pay_deposit']==0) return msg(-1, '', '您未缴纳押金');
        $param['money']=$user['deposit'];
        $param['status']=1;
        $param['addtime']=time();
        if(isset($param['cash_id'])) unset($param['cash_id']);
        if(isset($param['check_time'])) unset($param['check_time']);
        try{
            $num=$this->save(array('pay_deposit'=>0,'deposit'=>0),['user_id'=>$param['user_id']]);
            if(false === $num){
                return msg(-1, '', '提交失败');
            }else{
                $order_id=Db::name('user_cash')->insertGetId($param);
                return msg(1, array('order_id'=>$order_id,'money'=>$user['deposit']), '提交成功');
            }
        }catch(\Exception $e){
            return msg(-2, '', $e->getMessage());
        }
    }

    //意见反馈&投诉举报
    public function addFeedback($param){
        try{
            $param['addtime']=time();
            $result = Db::name('feedback')->insert($param);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', '未知错误');
            }
            return msg(1, "", '提交成功');
        }catch(\Exception $e){
            return msg(-2, '', $e->getMessage());
        }
    }

}